﻿using System;
using System.Collections;
using System.Collections.Generic;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine;
using UnityEngine.UI;

public class MomentPanel : AppUI
{
    public InputField commentInputField;
    public Text likeNum;
    public Image likeImg;
    public Text commentCount;
    public CommunityItem communityItem;
    public CommentInput commentInput;
    public Text commentBtnText;

    public Transform commentsParent;
    public CommentItem commentItemPref;

    UserMoment m_UserMoment;
    public UserMoment data => m_UserMoment;

    public Action onCommentsRefresh;
    public Action onLikesRefresh;

    public Button followBtn;
    public Text followText;
    public Color btnActiveColor;
    public Color btnDisactiveColor;

    public override void Awake()
    {
        base.Awake();

        this.commentItemPref.gameObject.SetActive(false);
    }

    public void Init(UserMoment userMoment)
    {
        m_UserMoment = userMoment;

        var touchObject = commentInputField.GetComponent<UITouchObject>();
        if (touchObject)
            touchObject.onPointerDownBegin = OnCommentPointerDownBegin;

        communityItem.Init(userMoment);

        GameDebug.Log($"moment panel :{userMoment.moment?.momentId}  comments:{userMoment.moment.comments?.GetListStr()}");

        InitComments(userMoment);

        RefreshLike(userMoment.moment.likes);
        RefreshFollow();

        commentInput.onInputEnd = this.OnEditEnd;
        commentInput.onSend = this.OnSendComment;
        HideCommentInput();
    }

    List<CommentItem> m_CommentItems = new List<CommentItem>();
    void InitComments(UserMoment userMoment)
    {
        if (userMoment.comments == null) return;

        UnityFunctions.ClearList(m_CommentItems);
        for (int i = 0; i < userMoment.comments.Count; i++)
        {
            NewCommentItem(userMoment.comments[i]);
        }
        OnCommentsUpdate();

        StartCoroutine(UnityFunctions.AdjustItemsLayout(transform));
    }

    CommentItem NewCommentItem(Comment data)
    {
        var newitem = Instantiate(commentItemPref, commentsParent);
        newitem.gameObject.SetActive(true);

        newitem.Init(data);

        m_CommentItems.Add(newitem);
        return newitem;
    }

    void OnCommentsUpdate()
    {
        commentCount.text = $"全部评论 {m_UserMoment.comments?.Count}";

        if (commentBtnText)
            commentBtnText.text = m_UserMoment.comments.Count.ToString();

        onCommentsRefresh?.Invoke();
    }

    private void OnEditEnd(string content)
    {
        this.commentInputField.text = content;
        HideCommentInput();
    }
    void ShowCommentInput()
    {
        this.commentInput.gameObject.SetActive(true);
    }
    void HideCommentInput()
    {
        this.commentInput.gameObject.SetActive(false);
    }

    private void OnSendComment(string msg)
    {
        GameDebug.Log($"momentId:{data.moment?.momentId}  OnSendComment:{msg}");

        RequestServerController.instance.ReqAddComment(MGame.instance.MUser.id,data.userId,
            data.moment.momentId, msg,(comment)=> 
            {
                m_UserMoment.moment.AddComment(comment);

                GameDebug.Log($"req add Comment end");
                HideCommentInput();

                if(comment != null)
                {
                    NewCommentItem(comment);
                    OnCommentsUpdate();

                    StartCoroutine(UnityFunctions.AdjustItemsLayout(commentsParent));
                }
            });
    }

    private void OnCommentPointerDownBegin(Vector2 vector)
    {
        OnClickComment();
    }

    public void OnClickComment()
    {
        ShowCommentInput();
    }
    public void OnClickLike()
    {
        bool likeOrNot = !myLike;
        RequestServerController.instance.ReqLikeMoment(MGame.instance.MUser.id, likeOrNot, this.m_UserMoment.userId, this.m_UserMoment.moment.momentId, (res) =>
        {
            if (likeOrNot)
                m_UserMoment.moment.AddLike(MGame.instance.MUser.id);
            else
                m_UserMoment.moment.RemoveLike(MGame.instance.MUser.id);

            RefreshLike(m_UserMoment.moment.likes);
            this.communityItem.RefreshLike(m_UserMoment.moment.likes);
        });
    }
    bool myLike;

    void RefreshLike(List<long> likes)
    {
        if (likes != null)
        {
            GameDebug.Log($"likes:{likes.GetListStr()}");

            likeNum.text = likes.Count.ToString();

            myLike = false;
            for (int i = 0; i < likes.Count; i++)
            {
                if (likes[i] == MGame.instance.MUser.id)
                {
                    myLike = true;
                    break;
                }
            }
            likeImg.gameObject.SetActive(myLike);
        }
        else
        {
            //GameDebug.Log($"likes is null");

            likeNum.text = "0";
            likeImg.gameObject.SetActive(false);
        }

        onLikesRefresh?.Invoke();
    }

    void RefreshFollow()
    {
        if (m_UserMoment.userId == MGame.instance.MUser.id)
        {
            followBtn.gameObject.SetActive(false);
        }
        else
        {
            followBtn.gameObject.SetActive(true);

            bool follow = MGame.instance.MUser.myFollows.Contains(m_UserMoment.userId);
            this.followBtn.image.color = follow ? btnDisactiveColor : btnActiveColor;
            followText.text = follow ? "已关注" : "关注";
        }
    }

    public void OnClickFollow()
    {
        bool follow = MGame.instance.MUser.myFollows.Contains(m_UserMoment.userId);

        RequestServerController.instance.ReqFollow(MGame.instance.MUser.id,m_UserMoment.userId, !follow, (ret) =>
        {
            RefreshFollow();
        });
    }

    // Update is called once per frame
    void Update()
    {

    }

}
